package com.msh.artascope.devcloud.service.util;

import com.msh.frame.client.define.StringDef;
import com.msh.frame.client.exception.BizException;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FreemarkerUtil {
  private static final String templatePath = "templates";
  private static final Configuration BASE_FREEMARKER_CFG= new Configuration(Configuration.VERSION_2_3_23);
  private static final String basePath;
  static {
    BASE_FREEMARKER_CFG.setTemplateLoader(new ClassTemplateLoader(Thread.currentThread().getContextClassLoader(),templatePath));
    BASE_FREEMARKER_CFG.setDefaultEncoding("UTF-8");
    BASE_FREEMARKER_CFG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    URL url =
        Thread.currentThread().getContextClassLoader().getResource(templatePath);
    String path = url.getPath().replaceAll("\\\\", "/");;
    if(path.startsWith("/")){
      path = path.substring(1);
    }
    basePath = path + StringDef.SLASH;
  }

  public static String getTemplatesPath(){
    return basePath;
  }


  public static String freemarkerProcess(Map map, String path) throws IOException, TemplateException {
    StringWriter buf = new StringWriter();
    BASE_FREEMARKER_CFG.getTemplate(path).process(map, buf);
    log.info("替换后: \n{}", buf.toString());
    return buf.toString();
  }

  public static String stringfreemarkerProcess(Map map, String templateStr)
      throws IOException, TemplateException {
    StringWriter buf = new StringWriter();
    Template template = new Template(null, templateStr, BASE_FREEMARKER_CFG);
    template.process(map, buf);

    return buf.toString();
  }


  /**
   * 替换ftl
   * @param map
   * @param ftlName
   * @return
   */
  public static String replaceFtl(Map<String,Object> map, String ftlName){
    try {
      return FreemarkerUtil.freemarkerProcess(map, ftlName);
    }catch (Exception e){
      log.error("FreemarkerUtil replaceFtl error", e);
      throw BizException.build("替换ftl文件失败");
    }
  }
}
